package com.etonedu.meals.http;

import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.bean.Result;
import com.etonedu.meals.http.xutils.NewXUtilsRequest;
import com.etonedu.meals.http.xutils.NewXUtilsResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;
import org.xutils.http.HttpMethod;

import java.lang.reflect.Type;

public class Request {

    private IGetUrl getUrl;

    public void setGetUrl(IGetUrl getUrl) {
        this.getUrl = getUrl;
    }

    public void getPublicUrl(final String apiCode, String environType) {
//        String apiCode = APICodeEnum.agw10111006.getApiCode();
//        String environType = EnvironmentType.TEST01.getType();
        String params = ParamsUtils.getURLParams(environType,apiCode);

        NewXUtilsRequest request = new NewXUtilsRequest("",params);
        request.requet(HttpUrl.URL, apiCode, HttpMethod.POST, new NewXUtilsResponse() {
            @Override
            public void response(String type, String result) {
                try {
                    LogUtils.d("apiCode = " + apiCode+",result = "+result);
                    Type typeToken = new TypeToken<Result>() {
                    }.getType();
                    Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                    Result r = gson.fromJson(result, typeToken);

                    String data = r.getData();

                    String deData = ParamsUtils.getDecrypt(apiCode,data);

                    LogUtils.d("apiCode = " + apiCode+",deData = " + deData);
                    JSONObject jsonObject = new JSONObject(deData);
                    String url = jsonObject.optString("fullUrl");
                    LogUtils.d("url = " + url);

                    if (getUrl != null) {
                        getUrl.success(url);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.e(e);
                    if (getUrl != null) {
                        getUrl.fail(e.getMessage());
                    }
                }
            }

            @Override
            public void error(String type, String msg) {
                LogUtils.e("msg = "+msg);
                if (getUrl != null) {
                    getUrl.fail(msg);
                }
            }
        });
    }
}
